package com.example.controller;

import com.example.common.Result;
import com.example.entity.Family;
import com.example.service.FamilyService;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/family")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class FamilyController {
    private final FamilyService familyService;

    public FamilyController(FamilyService familyService) {
        this.familyService = familyService;
    }

    @GetMapping
    public Result<List<Family>> getAllFamilies() {
        return Result.success(familyService.getAllFamilies());
    }

    @GetMapping("/admin/{adminUserId}")
    public Result<List<Family>> getFamilyByAdminUserId(@PathVariable Integer adminUserId) {
        List<Family> families = familyService.getFamilyByAdminUserId(adminUserId);
        if (families != null && !families.isEmpty()) {
            return Result.success(families);
        }
        return Result.error("未找到该管理员的家庭");
    }

    @GetMapping("/{id}")
    public Result<List<Family>> getFamilyById(@PathVariable Integer id) {
        Family family = familyService.getFamilyById(id);
        if (family != null) {
            return Result.success(Collections.singletonList(family));
        }
        return Result.error("未找到该家庭");
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteFamily(@PathVariable Integer id) {
        if (familyService.deleteFamily(id)) {
            return Result.success(null);
        }
        return Result.error("删除失败");
    }

    @PostMapping
    public Result<Void> addFamily(@RequestBody Family family) {
        // 添加详细的日志打印
        System.out.println("Received family request: " + family);
        
        // 验证必要参数
        if (family.getFamilyName() == null && family.getName() != null) {
            // 如果使用name字段，转换为familyName
            family.setFamilyName(family.getName());
        }
        
        if (family.getFamilyName() == null) {
            return Result.error("家庭名称不能为空");
        }
        
        // 如果没有提供adminUserId，使用默认值1
        if (family.getAdminUserId() == null) {
            family.setAdminUserId(1);
        }
        
        try {
            if (familyService.addFamily(family)) {
                return Result.success(null);
            }
            return Result.error("添加失败");
        } catch (Exception e) {
            System.err.println("Error adding family: " + e.getMessage());
            e.printStackTrace();
            return Result.error("添加家庭时发生错误：" + e.getMessage());
        }
    }

    @PutMapping
    public Result<Void> updateFamily(@RequestBody Family family) {
        if (familyService.updateFamily(family)) {
            return Result.success(null);
        }
        return Result.error("更新失败");
    }
} 